package com.example.staticdemo.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.example.staticdemo.config.ThreadPoolService;
import com.example.staticdemo.service.TestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class TestServiceImpl implements TestService {

    @Autowired
    private ThreadPoolService threadPoolService;

    @Override
    public void silkToWav(String sourceFile, String targetFile,String sh) {
        List<String> filePathList = traverseFolder(sourceFile);
        for (String source : filePathList) {
            String sourceName = FileUtil.getName(source);
            log.info("SILK 文件转码开始 source:{},date:{}",source, DateUtil.formatDate(new Date()));
            threadPoolService.insertVoicePool().execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Runtime run = Runtime.getRuntime();
//                        String[] runCmd = {sh, source, targetFile + "/" + sourceName,"wav"};
                        String[] runCmd = {sh, source,"wav"};
                        // Read output from FFmpeg process to handle any errors
                        Process process = run.exec(runCmd);
                        InputStream errorStream = process.getErrorStream();
                        BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream));
                        String line;
                        while ((line = errorReader.readLine()) != null) {
                            log.error(line);
                        }
                        int exitCode = process.waitFor();
                        if (exitCode == 0) {
                            log.info("Conversion completed successfully.");
                        } else {
                            log.error("Conversion failed with exit code: {}" , exitCode);
                        }
                    }catch (Exception e){
                        log.error("文件转换失败；{}",e);
                    }
                }
            });
        }
    }

    @Override
    public void pcmToWav(String sourceFileDir,String targetFileDir, String sh) {
        if(!FileUtil.exist(targetFileDir)){
            FileUtil.mkdir(targetFileDir);
        }
        List<String> filePathList = traverseFolder(sourceFileDir);
        for (String source : filePathList) {
            String sourceName = FileUtil.getPrefix(source);
            log.info("pcm 文件转码开始 source:{},date:{}",source, DateUtil.formatDate(new Date()));
            threadPoolService.insertVoicePool().execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Runtime run = Runtime.getRuntime();
//                        String[] runCmd = {sh, source, targetFile + "/" + sourceName,"wav"};
                        String[] runCmd = {sh, source,targetFileDir + "/" + sourceName + ".wav"};
                        // Read output from FFmpeg process to handle any errors
                        log.info("执行命令：{}", Arrays.toString(runCmd));
                        Process process = run.exec(runCmd);
                        InputStream errorStream = process.getErrorStream();
                        BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream));
                        String line;
                        while ((line = errorReader.readLine()) != null) {
                            log.error(line);
                        }
                        int exitCode = process.waitFor();
                        if (exitCode == 0) {
                            log.info("Conversion completed successfully.");
                        } else {
                            log.error("Conversion failed with exit code: {}" , exitCode);
                        }
                    }catch (Exception e){
                        log.error("文件转换失败；{}",e);
                    }
                }
            });
        }
    }

    public static List<String> traverseFolder(String folderPath) {
        List<String> filePathList = new ArrayList<String>();
        File folder = new File(folderPath);
        if (!folder.exists() || !folder.isDirectory()) {
            return filePathList;
        }
        for (File file : folder.listFiles()) {
            if (file.isFile()) {
                filePathList.add(file.getAbsolutePath());
            } else if (file.isDirectory()) {
                filePathList.addAll(traverseFolder(file.getAbsolutePath()));
            }
        }
        return filePathList;
    }
}
